import React, { useState, useRef } from 'react';
import { Card, Button, Upload, message, Input, Select, Slider } from 'antd';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';
import type { UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

const { Dragger } = Upload;
const { TextArea } = Input;
const { Option } = Select;

const VideoCreation: React.FC = () => {
  const [videoDescription, setVideoDescription] = useState<string>('');
  const [referenceFileUrl, setReferenceFileUrl] = useState<string>('');
  const [videoDuration, setVideoDuration] = useState<number>(15);
  const [videoStyle, setVideoStyle] = useState<string>('realistic');
  const [generatedVideoUrl, setGeneratedVideoUrl] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [tourVisible, setTourVisible] = useState<boolean>(false);
  
  // 创建ref引用
  const descriptionRef = useRef<HTMLDivElement>(null);
  const uploadRef = useRef<HTMLDivElement>(null);
  const settingsRef = useRef<HTMLDivElement>(null);
  const generateButtonRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  // 组织ref引用
  const tourRefs = {
    description: descriptionRef,
    upload: uploadRef,
    settings: settingsRef,
    generateButton: generateButtonRef,
    result: resultRef
  };
  
  // 定义steps配置
  const tourSteps = [
    {
      key: 'description',
      title: '视频描述',
      description: '详细描述您想要生成的视频内容，包括场景、人物、动作等要素。',
    },
    {
      key: 'upload',
      title: '上传参考文件',
      description: '可选步骤，上传图片或视频作为参考，帮助AI理解您的需求。',
    },
    {
      key: 'settings',
      title: '视频设置',
      description: '调整视频时长和选择视频风格，以获得更符合您预期的效果。',
    },
    {
      key: 'generateButton',
      title: '开始生成视频',
      description: '完成所有配置后，点击此按钮开始AI视频生成过程。',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处播放、下载或重新生成视频。',
    },
  ];
  
  // 显示引导
  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 参考文件上传成功`);
        setReferenceFileUrl(URL.createObjectURL(info.file.originFileObj as File));
      } else if (status === 'error') {
        message.error(`${info.file.name} 参考文件上传失败`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const handleVideoCreation = () => {
    if (!videoDescription) {
      message.warning('请先输入视频描述');
      return;
    }

    setLoading(true);
    // 模拟AI视频生成过程
    setTimeout(() => {
      message.success('视频生成完成');
      // 在实际应用中，这里会使用AI生成的视频URL
      setGeneratedVideoUrl('https://example.com/generated-video.mp4');
      setLoading(false);
    }, 8000);
  };

  return (
    <div className="p-4">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold">AI视频创作<TourGuideButton onClick={showTour} /></h2>
      </div>
      
      <Card title="视频描述" className="mb-4" ref={descriptionRef}>
        <TextArea
          rows={6}
          placeholder="请详细描述您想要生成的视频内容，例如：'一只可爱的小狗在草地上玩耍，阳光明媚的下午，画面温馨愉快'"
          value={videoDescription}
          onChange={(e) => setVideoDescription(e.target.value)}
        />
        <div className="text-sm text-gray-500 mt-2">
          <p>• 描述越详细，生成的视频越符合您的预期</p>
          <p>• 您可以指定场景、人物、动作、情感和风格等要素</p>
          <p>• 支持中文和英文描述</p>
        </div>
      </Card>

      <Card title="上传参考文件（可选）" className="mb-4" ref={uploadRef}>
        <Dragger {...uploadProps}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持图片或视频文件，系统将参考此内容生成相似风格的视频
          </p>
        </Dragger>
      </Card>

      <Card title="视频设置" className="mb-4" ref={settingsRef}>
        <div className="mb-4">
          <div className="mb-2">视频时长：{videoDuration} 秒</div>
          <Slider
            min={5}
            max={60}
            step={5}
            value={videoDuration}
            onChange={(value) => setVideoDuration(value)}
          />
          <div className="text-sm text-gray-500">建议选择 15-30 秒以获得最佳效果</div>
        </div>

        <div className="mb-4">
          <div className="mb-2">视频风格</div>
          <Select
            value={videoStyle}
            style={{ width: '100%' }}
            onChange={(value) => setVideoStyle(value)}
          >
            <Option value="realistic">写实风格</Option>
            <Option value="animation">动画风格</Option>
            <Option value="cartoon">卡通风格</Option>
            <Option value="watercolor">水彩风格</Option>
            <Option value="sketch">素描风格</Option>
            <Option value="oil">油画风格</Option>
          </Select>
        </div>
      </Card>

      <div ref={generateButtonRef}>
        <Button type="primary" onClick={handleVideoCreation} loading={loading} block size="large">
          开始生成视频
        </Button>
      </div>

      {generatedVideoUrl && !loading && (
        <Card title="生成结果" className="mt-4" ref={resultRef}>
          <div className="flex justify-center">
            <video 
              src={generatedVideoUrl}
              controls 
              className="max-w-full max-h-[500px]" style={{ 
                maxWidth: '100vw', 
                maxHeight: '60vh',
                margin: '0 auto'
              }}
            >
              您的浏览器不支持视频标签
            </video>
          </div>
          <div className="flex justify-center mt-4 space-x-4">
            <Button>下载视频</Button>
            <Button type="primary">重新生成</Button>
            <Button>调整参数</Button>
          </div>
        </Card>
      )}
      
      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </div>
  );
};

export default VideoCreation;